﻿using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;

using DotNetNuke.Entities.Users;
using DotNetNuke.Services.Tokens;


namespace DotNetNuke.Modules.UserDefinedTable
{


    public class GravatarPropertyAccess : IPropertyAccess
    {
        private string _email;

        public GravatarPropertyAccess(string Email)
        {
            this._email = Email.Trim().ToLowerInvariant();
        }

        public string GetProperty(string strPropertyName, string strFormat, CultureInfo formatProvider, UserInfo AccessingUser, Scope AccessLevel, ref bool PropertyNotFound)
        {
            strPropertyName = strPropertyName.ToLowerInvariant();
            switch (strPropertyName)
            {
                case "md5hash":
                    return PropertyAccess.FormatString(MD5Hash(this._email), strFormat);

                case "url":
                    return PropertyAccess.FormatString(string.Format("http://www.gravatar.com/avatar/{0}", MD5Hash(this._email)), strFormat);

                case "image":
                    return PropertyAccess.FormatString(string.Format("<img alt=\"gravatar\" src=\"http://www.gravatar.com/avatar/{0}\" />", MD5Hash(this._email)), strFormat);
            }
            PropertyNotFound = true;
            return string.Empty;
        }

        private static string MD5Hash(string value)
        {
            using (MD5CryptoServiceProvider provider = new MD5CryptoServiceProvider())
            {
                byte[] bytes = Encoding.ASCII.GetBytes(value);
                bytes = provider.ComputeHash(bytes);
                StringBuilder builder = new StringBuilder();
                foreach (byte num in bytes)
                {
                    builder.Append(num.ToString("x2"));
                }
                return builder.ToString();
            }
        }

        public CacheLevel Cacheability
        {
            get
            {
                return CacheLevel.notCacheable;
            }
        }

        //public CacheLevel DotNetNuke.Services.Tokens.IPropertyAccess.Cacheability
        //{
        //    get
        //    {
        //        return CacheLevel.notCacheable;
        //    }
        //}
    }
}

